package com.example.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        
        String path = req.getRequestURI();
        
        // 如果是登录相关的页面和资源，直接放行
        if (path.endsWith("login.jsp") || path.endsWith("register.jsp") 
                || path.endsWith("login") || path.endsWith("register")
                || path.contains("/css/") || path.contains("/js/") 
                || path.contains("/images/")) {
            chain.doFilter(request, response);
            return;
        }
        
        // 检查session中是否有用户信息
        HttpSession session = req.getSession(false);
        if (session != null && session.getAttribute("customer") != null) {
            chain.doFilter(request, response);
        } else {
            // 未登录则重定向到登录页面
            resp.sendRedirect("login.jsp");
        }
    }

    @Override
    public void destroy() {
    }
} 